import { View, Text } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { 
  Card, 
  Button, 
  Tag, 
  Grid, 
  GridItem,
  Dialog,
  Toast
} from '@nutui/nutui-react-taro'
import Taro, { useLoad, useDidShow } from '@tarojs/taro'
import './index.less'

export default function Member() {
  const [userInfo, setUserInfo] = useState(null)
  const [showUpgradeDialog, setShowUpgradeDialog] = useState(false)
  const [selectedPlan, setSelectedPlan] = useState(null)

  const memberPlans = [
    {
      id: 'basic',
      name: '基础会员',
      price: 99,
      duration: '1年',
      discount: '9折',
      benefits: ['洗护服务9折优惠', '专属客服', '优先预约'],
      popular: false
    },
    {
      id: 'premium',
      name: '高级会员',
      price: 199,
      duration: '1年',
      discount: '8.5折',
      benefits: ['洗护服务8.5折优惠', '专属客服', '优先预约', '免费上门取送', '衣物保险'],
      popular: true
    },
    {
      id: 'vip',
      name: 'VIP会员',
      price: 299,
      duration: '1年',
      discount: '8折',
      benefits: ['洗护服务8折优惠', '专属客服', '优先预约', '免费上门取送', '衣物保险', '专业护理建议'],
      popular: false
    }
  ]

  const memberBenefits = [
    { icon: '💰', title: '专享折扣', desc: '会员专享洗护服务折扣优惠' },
    { icon: '🚚', title: '免费配送', desc: '高级会员享受免费上门取送服务' },
    { icon: '⭐', title: '优先服务', desc: '会员用户享受优先预约和处理' },
    { icon: '🛡️', title: '衣物保险', desc: '高级会员衣物享受保险保障' },
    { icon: '👨‍💼', title: '专属客服', desc: '会员专属客服，贴心服务' },
    { icon: '💡', title: '护理建议', desc: 'VIP会员享受专业衣物护理建议' }
  ]

  useLoad(() => {
    checkLogin()
  })

  useDidShow(() => {
    checkLogin()
  })

  const checkLogin = () => {
    try {
      const user = Taro.getStorageSync('userInfo')
      setUserInfo(user) // 直接设置用户信息，允许为 null
    } catch (error) {
      console.log('获取用户信息失败')
      setUserInfo(null)
    }
  }

  const handleUpgrade = (plan) => {
    setSelectedPlan(plan)
    setShowUpgradeDialog(true)
  }

  const confirmUpgrade = () => {
    if (!selectedPlan) return
    
    setShowUpgradeDialog(false)
    
    // 跳转到支付页面
    Taro.navigateTo({
      url: `/pages/payment/index?type=member&level=${selectedPlan.name}&amount=${selectedPlan.price}`
    })
  }

  const getMemberStatus = () => {
    if (!userInfo) return null
    
    if (userInfo.isMember) {
      return {
        level: userInfo.memberLevel || '基础会员',
        expireDate: userInfo.memberExpireDate || '长期有效',
        status: 'active'
      }
    }
    
    return {
      level: '普通用户',
      expireDate: '',
      status: 'inactive'
    }
  }

  const memberStatus = getMemberStatus()

  if (!userInfo) {
    return (
      <View className='member-page'>
        {/* 未登录状态 */}
        <Card className='login-prompt-card'>
          <View className='login-prompt-content'>
            <Text className='prompt-icon'>⭐</Text>
            <Text className='prompt-title'>开通会员享受更多特权</Text>
            <Text className='prompt-subtitle'>登录后即可查看会员权益并开通会员</Text>
            <Button 
              type='primary'
              size='large'
              onClick={() => Taro.navigateTo({ url: '/pages/login/index' })}
              className='login-prompt-btn'
            >
              立即登录
            </Button>
          </View>
        </Card>

        {/* 会员权益预览 */}
        <Card className='benefits-card'>
          <Text className='card-title'>会员权益预览</Text>
          <Grid columns={2} gap={15}>
            {memberBenefits.slice(0, 4).map((benefit, index) => (
              <GridItem key={index}>
                <View className='benefit-item'>
                  <Text className='benefit-icon'>{benefit.icon}</Text>
                  <Text className='benefit-title'>{benefit.title}</Text>
                  <Text className='benefit-desc'>{benefit.desc}</Text>
                </View>
              </GridItem>
            ))}
          </Grid>
        </Card>
      </View>
    )
  }

  return (
    <View className='member-page'>
      {/* 会员状态卡片 */}
      <Card className='member-status-card'>
        <View className='member-header'>
          <View className='member-info'>
            <Text className='member-name'>{userInfo.nickname}</Text>
            <View className='member-level'>
              <Tag 
                color={memberStatus.status === 'active' ? '#ff6034' : '#969799'}
                textColor='white'
              >
                {memberStatus.level}
              </Tag>
            </View>
          </View>
          
          {memberStatus.status === 'active' && (
            <View className='member-expire'>
              <Text className='expire-label'>有效期至</Text>
              <Text className='expire-date'>{memberStatus.expireDate}</Text>
            </View>
          )}
        </View>
        
        {memberStatus.status === 'inactive' && (
          <View className='upgrade-prompt'>
            <Text className='prompt-text'>开通会员，享受更多优惠和特权</Text>
          </View>
        )}
      </Card>

      {/* 会员权益 */}
      <Card className='benefits-card'>
        <Text className='card-title'>会员权益</Text>
        <Grid columns={2} gap={15}>
          {memberBenefits.map((benefit, index) => (
            <GridItem key={index}>
              <View className='benefit-item'>
                <Text className='benefit-icon'>{benefit.icon}</Text>
                <Text className='benefit-title'>{benefit.title}</Text>
                <Text className='benefit-desc'>{benefit.desc}</Text>
              </View>
            </GridItem>
          ))}
        </Grid>
      </Card>

      {/* 会员套餐 */}
      <View className='plans-section'>
        <Text className='section-title'>会员套餐</Text>
        {memberPlans.map(plan => (
          <Card key={plan.id} className='plan-card'>
            <View className='plan-header'>
              <View className='plan-info'>
                <Text className='plan-name'>{plan.name}</Text>
                {plan.popular && (
                  <Tag color='#ff6034' textColor='white' size='small'>
                    推荐
                  </Tag>
                )}
              </View>
              <View className='plan-price'>
                <Text className='price-symbol'>¥</Text>
                <Text className='price-amount'>{plan.price}</Text>
                <Text className='price-duration'>/{plan.duration}</Text>
              </View>
            </View>
            
            <View className='plan-discount'>
              <Text className='discount-text'>享受{plan.discount}优惠</Text>
            </View>
            
            <View className='plan-benefits'>
              {plan.benefits.map((benefit, index) => (
                <View key={index} className='benefit-row'>
                  <Text className='benefit-check'>✓</Text>
                  <Text className='benefit-text'>{benefit}</Text>
                </View>
              ))}
            </View>
            
            <Button 
              type={plan.popular ? 'primary' : 'default'}
              size='large'
              onClick={() => handleUpgrade(plan)}
              className='upgrade-btn'
            >
              {memberStatus.status === 'active' ? '升级套餐' : '立即开通'}
            </Button>
          </Card>
        ))}
      </View>

      {/* 确认对话框 */}
      <Dialog
        visible={showUpgradeDialog}
        title='确认开通'
        content={selectedPlan ? `确认开通${selectedPlan.name}吗？费用为¥${selectedPlan.price}` : ''}
        onCancel={() => setShowUpgradeDialog(false)}
        onConfirm={confirmUpgrade}
      />
    </View>
  )
}